<template>
  <div id="map">
  </div>
  <div class="EnterpriseModal" v-if="isModalVisible" @close="closeModal">
    <div style="color:whitesmoke; 
    margin-bottom:0;
    width: 100%;
    background-color:rgb(0,63,72);
    " 
    >
    <div style="margin-left: 94.5%;background-color:rgba(0,32,31);padding-left: 0.2rem;padding-right: 0.2rem;;" @click="closeModal"><CloseOutlined /></div>
    </div>
    <EnterpriseModal :UnitCode="UnitCode" />
  </div>
</template>

<script setup name="BaiduMap">
import { onMounted, onBeforeUnmount, ref, watch } from 'vue';
import axios from 'axios';
import { CloseOutlined } from '@ant-design/icons-vue';
import { Modal,Button } from 'ant-design-vue';
import EnterpriseModal from '/@/views/Echarts/jgBigscreen/EnterpriseModal/index.vue';
import { Information } from '/@/api/jgBigscreen/jgBigscreen';
import normalIcon from '../assets/img/正常.png'; // 导入图片
import maintainceIcon from '../assets/img/维保.png'; // 导入图片
import hiddenIcon from '../assets/img/隐患.png'; // 导入图片
import alarmIcon from '../assets/img/预警.png'; // 导入图片
import fireIcon from '../assets/img/火警.png'; // 导入图片
import policeIcon from '../assets/img/警务站.png'; // 导入图片

// 定义响应式数据
const map = ref(null);
const isMapLoaded = ref(false);
const socket = ref(null);
const heartbeatInterval = ref(null);
const reconnectInterval = ref(null);
const markers = ref([]);
const ripples = ref({});
const dataChart = ref(null);
const isModalVisible = ref(false); // 控制弹窗显示状态
// 定义一个变量来记录是否点击了标记
const isMarkerClicked = ref(false);
const UnitCode = ref('');

// 加载百度地图 JavaScript API
const loadJScript = () => {
  const script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = '//api.map.baidu.com/api?type=webgl&v=3.0&ak=NI819Q7WHsYUgivpRLLl7kr0kyHfcRd5&callback=init';
  window.init = initMap;
  document.body.appendChild(script);
};

// 初始化地图
const initMap = () => {
  try {
    // 创建实例，应用自定义风格样式
    map.value = new BMapGL.Map('map', {
      enableMapClick: false,
    });
    // 应用自定义样式
    map.value.setMapStyleV2({
      styleId: '2d7095e48b0c441139213c00f977ddc3',
    });
    // 适当降低缩放级别
    map.value.centerAndZoom(new BMapGL.Point(93.5142008, 42.817404), 18);
    // 仅在需要时启用鼠标滚轮缩放
    map.value.enableScrollWheelZoom(true);
    isMapLoaded.value = true;
    map.value.setTilt(45); // 调整倾斜角度

    if (dataChart.value) {
      for (let i = 0; i < dataChart.value.length; i++) {
        const item = dataChart.value[i];
        // 根据 dominantType 设置图标
        let icon;
        if (item.dominantType === 'police_station') {
          icon = new BMapGL.Icon(policeIcon, new BMapGL.Size(20, 25));
        } else {
          icon = new BMapGL.Icon(normalIcon, new BMapGL.Size(20, 25));
        }

        if (item.bound) {
          try {
            // 解析 bound 字符串为数组
            const bounds = JSON.parse(item.bound);
            for (let j = 0; j < bounds.length; j++) {
              const bound = bounds[j];
              const point = new BMapGL.Point(bound.lng, bound.lat);
              // 使用设置好的图标
              const marker = new BMapGL.Marker(point, { icon: icon });
              // 保存 unitCode 到 marker
              marker.unitCode = item.unitCode;
              marker.state = 'normal'; // 初始状态为 normal
              markers.value.push(marker);

              // 为标记添加点击事件并设置事件名
              marker.addEventListener('click', () => {
                isMarkerClicked.value = true;
                UnitCode.value = item.unitCode; //获取企业id
                console.log(UnitCode.value)
                //console.log('Marker clicked');
                isModalVisible.value = true; // 点击时显示弹窗
                console.log(isModalVisible.value)
              });

              // 为标记添加鼠标悬浮事件
              const handleMouseOver = () => {
                const infoWindow = new BMapGL.InfoWindow(item.name);
                map.value.openInfoWindow(infoWindow, point);
              };
              marker.addEventListener('mouseover', handleMouseOver);

              // 为标记添加鼠标移出事件
              const handleMouseOut = () => {
                map.value.closeInfoWindow();
              };
              marker.addEventListener('mouseout', handleMouseOut);

              map.value.addOverlay(marker);
              //console.log('Marker added:', marker);
            }
          } catch (parseError) {
            //console.error('解析 bound 数据出错:', parseError);
          }
        }
      }
    }

    // 为地图添加点击事件监听器
    map.value.addEventListener('click', () => {
      if (isModalVisible.value &&!isMarkerClicked.value) {
        closeModal();
      }
      // 重置点击标记状态
      isMarkerClicked.value = false;
    });

    // 连接 WebSocket
    connect();
  } catch (error) {
    //console.error('地图初始化出错:', error);
  }
};

// 连接 WebSocket
const connect = () => {
  const randomNumber = Math.random(); // 生成一个随机数
  const url = `wss://zhxfzg.cn/wss/message-push/ws?userId=boardUser${randomNumber}`;
  socket.value = new WebSocket(url);

  socket.value.onopen = () => {
    //console.log('WebSocket 连接已打开');
    startHeartbeat();
    clearInterval(reconnectInterval.value);
  };

  socket.value.onmessage = (event) => {
    const message = event.data;
    // 判断消息是否包含“服务器收到: heartbeat”，包含则不进行后续解析
    if (message === '服务器收到: heartbeat') {
      return;
    }
    if (message === 'heartbeat') {
      showHaloForMarkers();
    } else {
      try {
        const data = JSON.parse(message);
        const enterpriseCode = data.enterpriseCode;
        const state = data.state;
        const latitude = data.latitude;
        const longitude = data.longitude;

        const point = new BMapGL.Point(longitude, latitude);

        if (state === 'normal') {
          if (ripples.value[enterpriseCode]) {
            map.value.removeOverlay(ripples.value[enterpriseCode]);
            delete ripples.value[enterpriseCode];
          }
        } else if (['fire', 'Maintenance', 'alarm', 'hidden'].includes(state)) {
          // 遍历标记，找到匹配的 unitCode
          markers.value.forEach((marker) => {
            if (marker.unitCode === enterpriseCode) {
              const markerPoint = marker.getPosition();
              marker.setIcon(createMarkerIcon(state));
              marker.state = state;
              showRippleAnimation(markerPoint, enterpriseCode, state);
            }
          });
          // 将地图中心移动到对应的坐标点
          map.value.panTo(point);
        }
      } catch (parseError) {
        //console.error('解析 WebSocket 消息出错:', parseError);
      }
    }
  };

  socket.value.onclose = () => {
    //console.log('WebSocket 连接已关闭，尝试重连');
    stopHeartbeat();
    reconnectInterval.value = setInterval(() => {
      connect();
    }, 5000);
  };

  socket.value.onerror = (error) => {
    //console.error('WebSocket 发生错误:', error);
  };
};

// 启动心跳
const startHeartbeat = () => {
  heartbeatInterval.value = setInterval(() => {
    if (socket.value && socket.value.readyState === WebSocket.OPEN) {
      socket.value.send('heartbeat');
    }
  }, 3000);
};

// 停止心跳
const stopHeartbeat = () => {
  clearInterval(heartbeatInterval.value);
};

// 为标记显示光晕
const showHaloForMarkers = () => {
  markers.value.forEach((marker) => {
    const point = marker.getPosition();
    let halo;
    if (map.value.getOverlays().some((overlay) => overlay === halo)) {
      map.value.removeOverlay(halo);
    }
    const size = new BMapGL.Size(50, 50);
    const pointPixel = map.value.pointToPixel(point);
    const haloPoint = map.value.pixelToPoint(new BMapGL.Pixel(pointPixel.x - size.width / 2, pointPixel.y - size.height / 2));
    const haloIcon = new BMapGL.Icon('https://dummyimage.com/50x50/ff0000/ffffff', size);
    halo = new BMapGL.Marker(haloPoint, { icon: haloIcon });
    halo.setZIndex(100); // 设置光晕覆盖物的层级
    map.value.addOverlay(halo);
    setTimeout(() => {
      if (halo) {
        map.value.removeOverlay(halo);
      }
    }, 1000);
  });
};

// 显示波纹动画
const showRippleAnimation = (point, enterpriseCode, state) => {
  if (ripples.value[enterpriseCode]) {
    map.value.removeOverlay(ripples.value[enterpriseCode]);
  }

  const ripple = createRipple(point, state);
  ripple.setZIndex(200); // 设置波纹覆盖物的层级，确保比标记层级高
  ripples.value[enterpriseCode] = ripple;
  map.value.addOverlay(ripple);

  // 为波纹覆盖物添加样式，让鼠标事件穿透
  const rippleElement = ripple.getDom();
  if (rippleElement) {
    rippleElement.style.pointerEvents = 'none';
  }

  // 模拟波纹动画
  let scale = 1;
  let opacity = 1;
  const interval = setInterval(() => {
    scale += 0.1;
    opacity -= 0.05;
    if (scale > 3 || opacity < 0) {
      scale = 1;
      opacity = 1;
    }
    const newSize = new BMapGL.Size(20 * scale, 20 * scale);
    const newIcon = createRippleIcon(newSize, opacity, state);
    ripple.setIcon(newIcon);
  }, 100);
};

// 创建波纹覆盖物
const createRipple = (point, state) => {
  const initialSize = new BMapGL.Size(20, 20);
  const initialIcon = createRippleIcon(initialSize, 1, state);
  return new BMapGL.Marker(point, { icon: initialIcon });
};

// 创建波纹图标
const createRippleIcon = (size, opacity, state) => {
  let color;
  switch (state) {
    case 'fire':
      color ='red';
      break;
    case 'Maintenance':
      color = 'purple';
      break;
    case 'alarm':
      color = 'orange';
      break;
    case 'hidden':
      color = 'yellow';
      break;
    default:
      color = 'green';
  }
  const svg = `
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="${size.width}" height="${size.height}" opacity="${opacity}">
      <circle cx="50" cy="50" r="40" fill="none" stroke="${color}" stroke-width="5" />
    </svg>
  `;
  const dataUrl = `data:image/svg+xml;base64,${btoa(unescape(encodeURIComponent(svg)))}`;
  return new BMapGL.Icon(dataUrl, size);
};

// 根据 state 状态创建标记图标
const createMarkerIcon = (state) => {
  let icon;
  switch (state) {
    case 'fire':
      icon = new BMapGL.Icon(fireIcon, new BMapGL.Size(20, 25));
      break;
    case 'Maintenance':
      icon = new BMapGL.Icon(maintainceIcon, new BMapGL.Size(20, 25));
      break;
    case 'alarm':
      icon = new BMapGL.Icon(alarmIcon, new BMapGL.Size(20, 25));
      break;
    case 'hidden':
      icon = new BMapGL.Icon(hiddenIcon, new BMapGL.Size(20, 25));
      break;
    default:
      icon = new BMapGL.Icon(normalIcon, new BMapGL.Size(20, 25));
  }
  return icon;
};

// 挂载生命周期钩子
onMounted(async () => {
  try {
    // 发起接口请求
    const response = await Information();
    dataChart.value = response;

    setTimeout(() => {
      // 开始加载百度地图 API
      loadJScript();
    }, 2000);
  } catch (error) {
    //console.error('请求接口出错:', error);
  }
});

// 销毁前生命周期钩子
onBeforeUnmount(() => {
  stopHeartbeat();
  clearInterval(reconnectInterval.value);
  if (socket.value) {
    socket.value.close();
  }
  if (map.value) {
    map.value.clearOverlays();
  }
});

// 关闭弹窗的方法
const closeModal = () => {
  isModalVisible.value = false;
  console.log('弹窗关闭');
};

// 点击事件处理函数
const handleOutsideClick = (event) => {
  const modal = document.querySelector('.EnterpriseModal');
  if (modal &&!modal.contains(event.target)) {
    closeModal();
  }
};
</script>

<style scoped lang="less">
#map {
  width: 100%;
  height: 100%;
  position: relative; /* 设置地图容器为相对定位 */
}

.EnterpriseModal {
  position: fixed; /* 固定定位，使弹窗悬浮在地图上方 */
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); /* 居中弹窗 */
  z-index: 300; /* 设置弹窗的层级高于地图 */
}
</style>